import { defineStore } from "pinia";
import { ref } from "vue";
import api from "@/utils/api";

export const useAuthStore = defineStore("auth", () => {
  const admin = ref(null);
  const token = ref(localStorage.getItem("token"));

  const login = async (credentials) => {
    try {
      const response = await api.post("/auth/login", credentials);
      token.value = response.data.token;
      localStorage.setItem("token", token.value);
      await fetchAdmin();
    } catch (error) {
      console.error("Login failed:", error);
      throw error;
    }
  };

  const logout = () => {
    admin.value = null;
    token.value = null;
    localStorage.removeItem("token");
  };

  const fetchAdmin = async () => {
    try {
      const response = await api.get("/auth/admin");
      admin.value = response.data;
    } catch (error) {
      console.error("Failed to fetch admin:", error);
      throw error;
    }
  };

  return { admin, token, login, logout, fetchAdmin };
});
